package com.leetcode.tree;

import com.study.common.TreeNode;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-19 11:17
 * @version: 1.0
 * @description: 给定一个二叉树，判断它是否是高度平衡的二叉树。
 * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
 **/
public class IsBalancedTree {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;

        return deepTree(root) != -1;
    }

    private int deepTree(TreeNode root) {

        if (root == null) return 1;


        int leftDeep = deepTree(root.left);
        int rightDeep = deepTree(root.right);

        if (leftDeep == -1 || rightDeep == -1 || Math.abs(leftDeep - rightDeep) > 1){
            return -1;
        }

        return Math.max(leftDeep,rightDeep) + 1;
    }
}
